package cn.itsource.org.service.impl;

import cn.itsource.common.mapper.BaseMapper;
import cn.itsource.org.domain.Menu;
import cn.itsource.org.mapper.MenuMapper;
import cn.itsource.org.service.IMenuService;
import cn.itsource.common.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    /**
     * 构建菜单树  for map
     * @return
     */
    @Override
    public List<Menu> menuTree() {
        List<Menu> menuAll = menuMapper.findAll();
        List<Menu> topMenu = new ArrayList<>();

        Map<Long, Menu> menuMap = menuAll.stream()
                .collect(Collectors.toMap(Menu::getId, s -> s));
        //补齐关系
        menuAll.forEach(menu -> {
            if(menu.getParentId() != null){
                //不是顶级
                Menu menu1 = menuMap.get(menu.getParentId());
                menu1.getChildren().add(menu);
            }else {
                topMenu.add(menu);
            }
        });
        return topMenu;
    }
}
